const axios = require('axios');

(async () => {
  console.log('🧪 综合测试：验证勋章显示功能修复');
  
  try {
    // 1. 登录用户
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'admin@campus.com',
      password: 'admin123'
    });
    
    const authToken = loginResponse.data.token;
    const userId = loginResponse.data.user.id;
    console.log(`✅ 用户登录成功: ID=${userId}`);
    
    // 2. 获取三种筛选下的勋章数据
    console.log('\n🏆 获取所有勋章数据...');
    
    // 获取"全部勋章" - 使用增大的limit参数
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges?limit=100', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    const allBadges = allBadgesResponse.data.badges;
    
    // 获取"我的勋章"
    const ownedBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=owned&limit=100', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    const ownedBadges = ownedBadgesResponse.data.badges;
    
    // 获取"可获得勋章"
    const availableBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=available&limit=100', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    const availableBadges = availableBadgesResponse.data.badges;
    
    // 3. 统计各种勋章数量
    console.log('\n📊 勋章数量统计:');
    console.log(`全部勋章: ${allBadges.length}个`);
    console.log(`已获得勋章: ${ownedBadges.length}个`);
    console.log(`可获得勋章: ${availableBadges.length}个`);
    console.log(`预期全部勋章 = 已获得 + 可获得: ${ownedBadges.length + availableBadges.length}个`);
    
    // 检查数量是否一致
    const isCountCorrect = allBadges.length === (ownedBadges.length + availableBadges.length);
    console.log(`勋章数量一致性: ${isCountCorrect ? '✅ 正确' : '❌ 不一致'}`);
    
    // 4. 验证"我的勋章"是否全部为已获得状态
    const ownedVerification = ownedBadges.every(badge => 
      badge.isOwned === true || (badge.status === 'minted' && badge.user_id === userId)
    );
    
    console.log('\n🔍 我的勋章验证:');
    if (ownedVerification) {
      console.log('✅ "我的勋章"全部为已获得状态');
    } else {
      console.log('❌ "我的勋章"中存在未获得的勋章');
      const invalidBadges = ownedBadges.filter(badge => 
        !(badge.isOwned === true || (badge.status === 'minted' && badge.user_id === userId))
      );
      console.log(`   发现 ${invalidBadges.length} 个问题勋章:`);
      invalidBadges.forEach(badge => {
        console.log(`   - ${badge.badge_name || '未命名'} (状态: ${badge.status}, isOwned: ${badge.isOwned})`);
      });
    }
    
    // 5. 验证"可获得勋章"是否全部为未获得状态
    const availableVerification = availableBadges.every(badge => 
      badge.isOwned === false && badge.status === 'available'
    );
    
    console.log('\n🔍 可获得勋章验证:');
    if (availableVerification) {
      console.log('✅ "可获得勋章"全部为未获得状态');
    } else {
      console.log('❌ "可获得勋章"中存在已获得的勋章');
      const invalidBadges = availableBadges.filter(badge => 
        !(badge.isOwned === false && badge.status === 'available')
      );
      console.log(`   发现 ${invalidBadges.length} 个问题勋章:`);
      invalidBadges.forEach(badge => {
        console.log(`   - ${badge.badge_name || '未命名'} (状态: ${badge.status}, isOwned: ${badge.isOwned})`);
      });
    }
    
    // 6. 检查特定问题勋章是否在全部勋章中显示
    const problemBadgeIds = ['potential_9', 'potential_10', 'potential_11'];
    const foundProblemBadges = allBadges.filter(badge => problemBadgeIds.includes(badge.id));
    
    console.log('\n🔍 问题勋章验证:');
    console.log(`在全部勋章中找到问题勋章: ${foundProblemBadges.length}/${problemBadgeIds.length}`);
    
    if (foundProblemBadges.length === problemBadgeIds.length) {
      console.log('✅ 所有问题勋章已正确显示在全部勋章中');
      
      // 显示找到的问题勋章
      console.log('找到的问题勋章:');
      foundProblemBadges.forEach(badge => {
        console.log(`  - ID: ${badge.id}, 名称: ${badge.badge_name}, 状态: ${badge.status}`);
      });
    } else {
      console.log('❌ 部分问题勋章在全部勋章中仍然缺失');
      
      // 显示缺失的勋章
      const missingIds = problemBadgeIds.filter(id => !allBadges.some(badge => badge.id === id));
      console.log(`  缺失的勋章ID: ${missingIds.join(', ')}`);
      
      // 检查这些勋章是否在可获得勋章中存在
      const inAvailable = availableBadges.filter(badge => missingIds.includes(badge.id));
      if (inAvailable.length > 0) {
        console.log(`  这些勋章在"可获得勋章"中存在 ${inAvailable.length}/${missingIds.length} 个`);
      }
    }
    
    // 7. 检查潜在勋章(potential_)数量
    const potentialInAll = allBadges.filter(badge => String(badge.id).startsWith('potential_')).length;
    const potentialInAvailable = availableBadges.filter(badge => String(badge.id).startsWith('potential_')).length;
    
    console.log('\n🔍 潜在勋章数量验证:');
    console.log(`全部勋章中的潜在勋章: ${potentialInAll}个`);
    console.log(`可获得勋章中的潜在勋章: ${potentialInAvailable}个`);
    
    if (potentialInAll === potentialInAvailable) {
      console.log('✅ 潜在勋章数量一致');
    } else {
      console.log('❌ 潜在勋章数量不一致');
      console.log(`   差异: ${Math.abs(potentialInAll - potentialInAvailable)}个`);
    }
    
    // 8. 总结
    console.log('\n📝 最终验证结果:');
    
    if (isCountCorrect && ownedVerification && availableVerification && 
        foundProblemBadges.length === problemBadgeIds.length && 
        potentialInAll === potentialInAvailable) {
      console.log('✅ 勋章显示功能已完全修复!');
    } else {
      console.log('❌ 勋章显示功能仍有问题需要解决:');
      if (!isCountCorrect) console.log('   - 勋章数量不一致');
      if (!ownedVerification) console.log('   - "我的勋章"包含未获得勋章');
      if (!availableVerification) console.log('   - "可获得勋章"包含已获得勋章');
      if (foundProblemBadges.length !== problemBadgeIds.length) console.log('   - 问题勋章在全部勋章中缺失');
      if (potentialInAll !== potentialInAvailable) console.log('   - 潜在勋章数量不一致');
    }
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    if (error.response) {
      console.error('详细错误:', error.response.data);
    }
  }
})(); 